package com.eggplant.timetools;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import uij.wf.kf.pouzzt.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.eggplant.timetools.ControlRotate3D.ControlRotate3DListener;
import com.eggplant.timetools.base.BaseListAcitvity;
import com.eggplant.timetools.bean.TaskItem;
import com.eggplant.timetools.db.TaskItemDb;
import com.eggplant.timetools.utils.MyLog;
import com.eggplant.timetools.utils.PreferencesData;
import com.eggplant.timetools.utils.SystemUtils;
import com.eggplant.timetools.view.Alert_Dialog;
import com.eggplant.timetools.view.MyTitleView;
import com.eggplant.timetools.view.TimerView;


public class EggpMainActivity extends BaseListAcitvity<TaskItem> implements ControlRotate3DListener {

	// variables
	private List<TaskItem> mData;
	private final static int DIALOG_COMMENT_TEXT = 200;
	private final static int DIALOG_ABOUT = 100;
	
	MyTitleView myTitleView;
	PopupWindow popupWindow;
	private static final int SHOWADATER=1;
	private static final int SAVE_RESTORE_DIALOG=2;
	public static final String RECEIVER_DATA_CHANGE = "com.eggleplant.dataChange";
	BroadcastReceiver dataChangeReceiver= new DataChangeReceiver();
	BroadcastReceiver serviceReceiver= new TaskContrReceiver();
    private View mContainer;
    private View mTopView;
    private TimerView mBottomView;
    private final static int SHOWTIMER=1;
    private final static int SHOMAINPAGE=2;
    private Button mTimerBt;
    private String[] intervWays;
    private int[] item_icons;
    private static final int DIALOG_SAVE=1;
    private CharSequence[] items = new CharSequence[2];

    
	Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case 1:
				mListAdapter.update();
				break;
			case 2:
				showDialog(DIALOG_SAVE, new Bundle());
				break;
				
			case 3:
				String content=(String) msg.obj;
				SystemUtils.showToast(getApplicationContext(), content);
				break;
			case 4:
				finish();
				break;
			}
			
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		initData(false);
		initBroadcast();
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
	
		
	};
	
	

	@Override
	protected void onPause() {
		if(mBottomView!=null){
			mBottomView.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		if(mBottomView!=null){
			mBottomView.start();
		}
		super.onResume();
	}

	@Override
	protected void initViews() {
		super.initViews();
		initTitleBar();
		addListViewHeard();
		mContainer=findViewById(R.id.container);
		mTopView=findViewById(R.id.top_main);
		mBottomView=(TimerView)findViewById(R.id.bottom_timerview);
		mTimerBt=(Button)findViewById(R.id.show_timer_bt);
	}



	@Override
	protected void initListeners() {
		super.initListeners();
		mTimerBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				do3DAnimation(mContainer, SHOWTIMER);
				
			}
		});
	}



	private void addListViewHeard(){
		View headerView = findViewById(R.id.create_headerview);
		ImageView iconIV =(ImageView) headerView
		.findViewById(R.id.item_icon);
		iconIV.setImageResource(R.drawable.icon_num_add);
		TextView item_title = (TextView) headerView
				.findViewById(R.id.item_title);
		item_title.setText("创建新计划");
		headerView.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				 Intent i = new Intent(EggpMainActivity.this,TaskTypeActivity.class);
				 startActivity(i);
				
			}
			
		});
	}
	
	
	
	@Override
	public void onBackPressed() {
		if(mBottomView.isShown())
		do3DAnimation(mContainer, SHOMAINPAGE);
		else{
			if(PreferencesData.getTaskKey(getApplicationContext())!=-1){
				Intent intent = new Intent();//回到桌面不退出
				intent.setAction("android.intent.action.MAIN");
				intent.addCategory("android.intent.category.HOME");
				startActivity(intent);
			}else{
				super.onBackPressed();
			}
		}
	}



	private void initBroadcast(){
		IntentFilter filter = new IntentFilter(
				RECEIVER_DATA_CHANGE);	
		registerReceiver(dataChangeReceiver, filter);
	
		IntentFilter filter1 = new IntentFilter(
				TaskItem.START);				
		registerReceiver(serviceReceiver, filter1);
		
		
	}
	

	@Override
	protected void onListItemClick(TaskItem data, int position,
			View view) {
		 Intent i = new Intent(this,TaskDetailActivity.class);
		 Bundle bundle = new Bundle();
		 bundle.putParcelable("task", data);
		 i.putExtras(bundle);
		 startActivity(i);
		 
		super.onListItemClick(data, position, view);
	}

	@Override
	protected View getItemView(final TaskItem data, View convertView,
			int position) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = getLayoutInflater().inflate(
					R.layout.plan_task_item, null);
			holder = new ViewHolder();
			holder.item_icon = (ImageView) convertView
					.findViewById(R.id.item_icon);
			holder.item_start = (TextView) convertView
					.findViewById(R.id.item_right_img);
			holder.item_iterv_type = (TextView) convertView
					.findViewById(R.id.item_interv_type);
			holder.item_title = (TextView) convertView
					.findViewById(R.id.item_title);
			holder.item_desc = (TextView) convertView
					.findViewById(R.id.item_desc);
			holder.item_action_bg =  convertView
					.findViewById(R.id.item_action_bg);
			holder.item_left_bg =  convertView
					.findViewById(R.id.item_left_chart_bg);
			holder.item_right_bg =  convertView
					.findViewById(R.id.item_right_img_bg);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		int index =position%10;
		holder.item_icon.setImageResource(item_icons[index]);
		if(data!=null){
			holder.item_title.setText(data.target);
			holder.item_desc.setText(data.timeInte+"分钟提示一次（共"+data.timeLeng+"分钟）");
		}
		
		holder.item_action_bg.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				return true;
			}
			
		});
		if(intervWays!=null&&data!=null)
		holder.item_iterv_type.setText(intervWays[intervWays.length-1-data.noticeWays]);
		Long runningT=PreferencesData.getTaskKey(getApplicationContext());
		final long startTime =PreferencesData.getTaskStartTime(getApplicationContext());
		
			if(runningT!=-1&&data!=null&&data.buildTime==runningT){
				if(System.currentTimeMillis()-startTime>data.timeLeng*60*1000){
					PreferencesData.setTaskKey(getApplicationContext(), -1);
					holder.item_start.setText("开始");
					holder.item_start.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_task_start, 0, 0, 0);
				}else{	
					
					new Thread(new Runnable(){

						@Override
						public void run() {
							if(!SystemUtils.isServiceRunning(getApplicationContext(), ControlService.class.getName())){
								
								data.timeUsed=startTime;
								OnlyTaskItem.setTaskItem(getApplicationContext(), data);
								Intent i = new Intent(TaskItem.START);
								i.putExtra("control", "start");
								sendBroadcast(i);
							}
							
							
						}
						
					}).start();
			
					holder.item_start.setText("停止");
					holder.item_start.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_task_pause, 0, 0, 0);
				}
			}else{
				holder.item_start.setText("开始");
				holder.item_start.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_task_start, 0, 0, 0);
			}
		
		
		holder.item_right_bg.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				TextView iv =(TextView) v.findViewById(R.id.item_right_img);
				if(PreferencesData.getTaskKey(getApplicationContext())==-1){
					PreferencesData.setTaskStartTime(getApplicationContext(), System.currentTimeMillis());					 
						iv.setText("停止");
						iv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_task_pause, 0, 0, 0);
				/*	String test=null;
					test.substring(1);*/
						data.timeUsed=System.currentTimeMillis();
					OnlyTaskItem.setTaskItem(getApplicationContext(), data);
					Intent i = new Intent(TaskItem.START);
					i.putExtra("control", "start");
					sendBroadcast(i);
					if(data.timeLeng>180&&data.noticeWays==1){
						SystemUtils.showToast(getApplicationContext(), "语音报时提示最大支持三小时！已经转为铃声提示");
					}
				}else{
					if(PreferencesData.getTaskKey(getApplicationContext())!=data.buildTime){
						Toast.makeText(getApplicationContext(), "同一时间内,只能执行一项计划!", Toast.LENGTH_SHORT).show();
						return;
					}
					 iv.setText("开始");
					 iv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_task_start, 0, 0, 0);
					OnlyTaskItem.setTaskItem(getApplicationContext(), null);
					Intent i = new Intent(TaskItem.START);
					i.putExtra("control", "stop");
					sendBroadcast(i);
					
				}
			}
		});
		
		holder.item_left_bg.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i= new Intent(getApplicationContext(), TaskLogsActivity.class);
				i.putExtra("buildTime", data.buildTime);
				startActivity(i);	
				
			}
		});
		return convertView;
	}
	
	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id,Bundle bundle) {
		// TODO Auto-generated method stub
		switch(id){
		case DIALOG_COMMENT_TEXT : {
			final View view = LayoutInflater.from(this).inflate(
					R.layout.comments, null);
			final TextView title = (TextView) view.findViewById(R.id.title);
			final TextView body = (TextView) view.findViewById(R.id.text);
			Button send_now_button = (Button) view
					.findViewById(R.id.send_now);
			Button cancel_button = (Button) view
					.findViewById(R.id.cancel_btn);

			send_now_button.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					SystemUtils.hideKeyboard(title);
					String commentTitle = title.getText().toString();
					String commentText = body.getText().toString();

					if (commentTitle.length() == 0) {
						SystemUtils.showToast(getApplicationContext(),
								"请留下联系方式");
						return;
					}

					if (commentText.length() == 0) {
						SystemUtils.showToast(getApplicationContext(),
								"数据为空！");
						return;
					}

					dismissDialog(DIALOG_COMMENT_TEXT);
					//sendCommens(commentTitle, commentText);

				}
			});

			cancel_button.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					SystemUtils.hideKeyboard(title);
					dismissDialog(DIALOG_COMMENT_TEXT);
				}
			});

			AlertDialog.Builder builder = new AlertDialog.Builder(
					EggpMainActivity.this).setTitle(
					R.string.send_comment_title).setView(view);
			return builder.create();
		}
			 
		case DIALOG_SAVE : {
			items[0] = "备份数据到SD卡";
			items[1] = "从SD卡恢复数据";
			LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View dialogView = (View) inflate.inflate(
					R.layout.save_restore_list_dialog, null);	
			Alert_Dialog.Builder builder = new Alert_Dialog.Builder(
					EggpMainActivity.this)
					.setTitle("提示")
					.setAdapter(new ArrayAdapter(EggpMainActivity.this,R.layout.save_restore_list_dialog,items),
			  new DialogInterface.OnClickListener(){
				 public void onClick(DialogInterface dialog,int num){
					 switch(num){
	               
	                 case 0: 
	                	 backOrRebackAllData(true);
	                         break;
	                 case 1: 
	                 backOrRebackAllData(false);
	                         break;
					 }
				 }
			 }).setNegativeButton("取消", new DialogInterface.OnClickListener(){
				 public void onClick(DialogInterface dialog, int which){

				 }
			 });
			Dialog dialog= builder.create();
			dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			return builder.create();
		}
		}
		return super.onCreateDialog(id,bundle);
	}
	
	private void backOrRebackAllData(final boolean isback){
		new Thread(new Runnable(){

			@Override
			public void run() {
				Message msg = new Message();
				if(!isback){
					if(SystemUtils.rebackAllData()){						
						msg.obj="恢复数据成功！";
						mHandler.sendEmptyMessageDelayed(4, 1000);
					}
					
					else{
						msg.obj="恢复数据失败,请重试！";
					}
				}
				else{
					if(SystemUtils.backupAlldata())
				  msg.obj="成功到sdcard/eggplant_timetools目录";
					else{
						msg.obj="备份数据失败,请重试！";
					}
				}
				msg.what=3;
				mHandler.sendMessage(msg);
				
			}
			
		}).start();
	}

	@Override
	protected List<TaskItem> getListData() {
		return mData;
	}

	@Override
	public ListView getListView() {
		return (ListView) findViewById(android.R.id.list);
	}

	@Override
	protected int getResLayoutId() {
		return R.layout.activity_eggp_main;
	}

	@Override
	protected void initVariables() {		
		super.initVariables();
		mData = new ArrayList<TaskItem>();
		intervWays=getResources().getStringArray(R.array.task_ways_list);
		item_icons=new int[]{
				R.drawable.icon_num_0,	
				R.drawable.icon_num_1,	
				R.drawable.icon_num_2,	
				R.drawable.icon_num_3,	
				R.drawable.icon_num_4,	
				R.drawable.icon_num_5,	
				R.drawable.icon_num_6,	
				R.drawable.icon_num_7,	
				R.drawable.icon_num_8,	
				R.drawable.icon_num_9,	
			};

	}

	private void initData(final boolean isRefresh) {
		new Thread(new Runnable(){

			@Override
			public void run() {
								mData.clear();
				mData.addAll(TaskItemDb.getInstance(getApplicationContext()).getTaskList(isRefresh).values());
				Collections.sort(mData, new Comparator<TaskItem>(){

					@Override
					public int compare(TaskItem lhs, TaskItem rhs) {
						if(lhs.nextTime>rhs.nextTime){//最后使用数据在最前面
							return -1;
						}else if(lhs.nextTime==rhs.nextTime){
							if(lhs.buildTime>rhs.buildTime)
								return -1;
							else
								return 0;
						}else 
							return 1;
					}
					
				});
				mHandler.sendEmptyMessage(SHOWADATER);
			}
			
		}).start();
		
	
	}
	

	
	public static class ViewHolder {
		/** 任务类型图标 **/
		ImageView item_icon;
		/** 任务类型标题 **/
		TextView item_title,item_start,item_iterv_type;
		TextView item_desc;		
		View item_action_bg,item_left_bg,item_right_bg;
	}
	
	
	
	/**
	 * 初始化标题栏
	 */
	private void initTitleBar() {
		// 由于是主界面，需调用两个参数的构造，这个界面是没有返回箭头的，且不响应返回事件
		myTitleView = new MyTitleView(this, true);
		myTitleView.setTitle(R.string.app_name);
		myTitleView.addMenuView(1, R.drawable.menu_more,
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {					
						showMoreOptions(v);					
					}
				});	
		
		myTitleView.addMenuView(2, R.drawable.menu_set,
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						 Intent i = new Intent(EggpMainActivity.this,SettingEggActivity.class);
						 startActivity(i);
					}
				});
	}

	/**
	 * 更多选项
	 */
	private void showMoreOptions(View view) {
		LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		ViewGroup menuView = (ViewGroup) mLayoutInflater.inflate(
				R.layout.main_page_more, null, true);

		popupWindow = new PopupWindow(menuView,
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT, true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(view, SystemUtils.dip2px(this, -10),
				SystemUtils.dip2px(this, -6));
		popupWindow.update();
		setOnclickEvent(menuView);
	}

	public void setOnclickEvent(ViewGroup menuView) {

		LinearLayout mLayout1 = (LinearLayout) menuView
				.findViewById(R.id.setting_recommand);
		mLayout1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				sendToFriend();
				popupWindow.dismiss();
			}
		});

		LinearLayout mLayout2 = (LinearLayout) menuView
				.findViewById(R.id.setting_gift);
		mLayout2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(DIALOG_SAVE, new Bundle());
				popupWindow.dismiss();
			}
		});
		LinearLayout mLayout5 = (LinearLayout) menuView
				.findViewById(R.id.setting_about);
		mLayout5.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 关于
				aboutPage();
				popupWindow.dismiss();
			}
		});
	}
	
	
	/**
	 * 关于软件页面
	 */
	protected void aboutPage()
	{
		Intent aboutIntent = new Intent(EggpMainActivity.this, AboutPage.class);
		startActivity(aboutIntent);
	}
	
	/**
	 * 推荐好友
	 */
	protected void sendToFriend() {
		String url = "";
		try {
			url = "file:///"
					+ getPackageManager().getApplicationInfo(getPackageName(),
							0).sourceDir;
		} catch (Exception e) {
			e.printStackTrace();
		}

		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		shareIntent.putExtra(Intent.EXTRA_SUBJECT,
				getString(R.string.tofriend_subject));
		shareIntent.putExtra(Intent.EXTRA_TEXT,
				getResources().getString(R.string.tofriend_subject_text));
		shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
		shareIntent.setClass(this, ShareResolverActivity.class);
		shareIntent.setType("text/plain");
		startActivity(shareIntent);
	}

	

	@Override
	protected boolean isListEmpty() {
		return false;
	}
	
	
	class DataChangeReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			if(arg1.getAction().equalsIgnoreCase(RECEIVER_DATA_CHANGE)){
				MyLog.i("ydy", "DataChangeReceiver onReceive****");
				initData(true);
			}
			
		}
		
	}
	
	@Override
	protected void onDestroy() {
    	unregisterReceiver(dataChangeReceiver);
    	unregisterReceiver(serviceReceiver);
		super.onDestroy();
	}



	@Override
	public void onAnimationEnd(int requestCode) {
		// TODO Auto-generated method stub
		
	}
	
	


	@Override
	public void onSwitchView(int requestCode) {
		if(requestCode==SHOWTIMER){
			mTopView.setVisibility(View.GONE);
			mBottomView.setVisibility(View.VISIBLE);
			mBottomView.requestFocus();
		}else{
			mBottomView.setVisibility(View.GONE);
			mTopView.setVisibility(View.VISIBLE);
			mTopView.requestFocus();
		}
		
	}

	
	
	private void do3DAnimation(View v, int requestCode) {
		ControlRotate3D controlRotate3D = new ControlRotate3D();
		controlRotate3D.setControlRotate3DListener(this);
		controlRotate3D.applyRotation(v, 0, 90, 500, requestCode);
	}

}
